package com.bjpowernode.aop;

import com.bjpowernode.annotations.DataScope;
import com.bjpowernode.entities.TRole;
import com.bjpowernode.entities.TUser;
import com.bjpowernode.querys.BaseQuery;
import com.bjpowernode.utils.LoginInfoUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Aspect
public class DataScopeAspect {
    @Around(value = "@annotation(com.bjpowernode.annotations.DataScope)")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        DataScope dataScope = methodSignature.getMethod().getDeclaredAnnotation(DataScope.class);
        String tableAlias = Objects.requireNonNull(dataScope).tableAlias();
        String columnName = dataScope.columnName();
        TUser tUser = LoginInfoUtil.getCurrentLoginUser();
        List<TRole> roleList = tUser.getTRoleList();
        List<String> roleNameList = new ArrayList<>();
        for (TRole role : roleList)
            roleNameList.add(role.getRole());
        if (!roleNameList.contains("admin")) {
            Object params = joinPoint.getArgs()[0];
            if (params instanceof BaseQuery baseQuery)
                baseQuery.setFilterSQL(" and " + tableAlias + "." + columnName + " = " + tUser.getId());
        }
        return joinPoint.proceed();
    }
}
